import { useState, useEffect } from 'react'
function TodoList() {
    const [todos, setTodos] = useState([]) // 代办列表
    const [inputValue, setInputValue] = useState('') // 输入框的值

    // 添加代办
    const add = () => {
        const todo = {
            id: Date.now(),
            text: inputValue,
            completed: false
        }
        setTodos([...todos, todo])
    }
    // 删除代办
    const deleteItem = (id) => {
        setTodos(todos.filter(todo => todo.id !== id))
    }

    // 切换状态
    const toggle = (id) => {
        setTodos(todos.map(todo => {
            if (todo.id === id) {
                return {
                    ...todo,
                    completed: !todo.completed
                }
            } else {
                return todo
            }
        }))
    }

    return (
        <div className="container">
            <h1>Todo List</h1>
            <div className="top">
                <input
                    type="text"
                    placeholder="请输入代办事项"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                />
                <button onClick={add}>添加</button>
            </div>
            <div className="bottom">
                <ul>
                    {todos.map((item) => {
                        return <li key={item.id}>
                            <input type="checkbox" value={item.completed} onChange={() => toggle(item.id)} />
                            <span style={{ textDecoration: item.completed ? 'line-through' : 'none' }}>{item.text}</span>
                            <button onClick={() => deleteItem(item.id)}>删除</button>
                        </li>
                    })}

                </ul>
            </div>
        </div>
    )
}

export default TodoList;